#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <iostream>
#include <string>
#include <thread>
#include <cstring>

void receiveMessages(int socket) {
    char buffer[1024];
    while (true) {
        memset(buffer, 0, sizeof(buffer));
        int bytes = recv(socket, buffer, sizeof(buffer) - 1, 0);
        if (bytes <= 0) {
            std::cout << "与服务器断开连接" << std::endl;
            break;
        }
        std::cout << buffer;
    }
}

int main(int argc, char* argv[]) {
    std::string serverIP = "119.29.166.25";
    uint16_t port = 8080;
    
    if (argc >= 2) serverIP = argv[1];
    if (argc >= 3) port = static_cast<uint16_t>(std::atoi(argv[2]));
    
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
        std::cerr << "创建socket失败" << std::endl;
        return 1;
    }
    
    struct sockaddr_in serverAddr;
    memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(port);
    
    if (inet_pton(AF_INET, serverIP.c_str(), &serverAddr.sin_addr) != 1) {
        std::cerr << "无效的服务器地址: " << serverIP << std::endl;
        close(sock);
        return 1;
    }
    
    if (connect(sock, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) {
        std::cerr << "连接服务器失败: " << serverIP << ":" << port << std::endl;
        close(sock);
        return 1;
    }
    
    std::cout << "已连接到服务器 " << serverIP << ":" << port << std::endl;
    std::cout << "输入消息发送，输入 '/quit' 退出，输入 '/count' 查看在线人数" << std::endl;
    
    // 启动接收消息的线程
    std::thread recvThread(receiveMessages, sock);
    recvThread.detach();
    
    // 发送消息
    std::string message;
    while (std::getline(std::cin, message)) {
        message += "\n";
        if (send(sock, message.c_str(), message.length(), 0) < 0) {
            std::cerr << "发送消息失败" << std::endl;
            break;
        }
        if (message.find("/quit") == 0) {
            break;
        }
    }
    
    close(sock);
    return 0;
}